package com.sunxd.zstudy.jvm.classload;

import java.io.*;

/**
 * @author: sun.xd
 * @date: 2021-10-20 15:54
 **/
public class T03_MyClassLoader extends ClassLoader {

    private String classPath;

    public T03_MyClassLoader(String classPath) {
        this.classPath = classPath;
    }


    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {

        byte[] classData = new byte[0];
        try {
            classData = getDate(name);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (classData != null) {
            // 将class的字节码数组转换成Class类的实例
            return defineClass(name, classData, 0, classData.length);
        }
        return null;
    }

    //返回类的字节码
    private byte[] getDate(String className) throws IOException {
        InputStream in = null;
        ByteArrayOutputStream out = null;
        String path = classPath + File.separatorChar +
                className.replace('.', File.separatorChar) + ".class";
        try {
            in = new FileInputStream(path);
            out = new ByteArrayOutputStream();
            byte[] buffer = new byte[2048];
            int len = 0;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            return out.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            in.close();
            out.close();
        }
        return null;
    }


}
